<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/1/18
 * Time: 9:47
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\api\controller;

use app\api\model\mysql\MallApplygoods;
use app\api\model\mysql\MallCollect;
use app\api\model\mysql\MallOrder;
use app\api\model\mysql\MallOrderGoods;
use app\api\model\mysql\MallSetting;
use app\api\model\mysql\MallUser;
use app\common\lib\Show;
use app\common\lib\Status;
use app\common\lib\Str;
use app\common\model\MallCommissionLevel;
use think\facade\Log;

class User extends Base
{
    /**
     * 更新用户信息
     * @return \think\response\Json
     */
    public function updateByUserInfo()
    {
        $avatarUrl = $this->request->param('avatarUrl', '', 'trim');
        $openid = $this->request->param('openid', '', 'trim');
        $nickName = $this->request->param('nickName', '', 'trim');
        $data = [
            "avatarUrl" => $avatarUrl,
            "nickName" => htmlspecialchars_decode($nickName)
        ];
        //查询用户是否存在
        try {
            $user = (new MallUser())->getUserByList($openid);
        } catch (\Exception $e) {
            Log::error("user_update:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error, "发生错误");
        }
        if (!$user) {
            return Show::json_show(Status::mini_error, "请关闭重试");
        }
        try {
            $result = $user->save($data);
        } catch (\Exception $e) {
            Log::error("user_update_save:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error, "发生错误");
        }
        if ($result) {
            try {
                $wechat = (new MallUser())->getUserByList($openid);
            } catch (\Exception $e) {
                Log::error("user_update:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
                return Show::json_show(Status::mini_error, "发生错误");
            }
            if ($wechat) {
                return Show::json_show(Status::mini_normal, "操作成功", $wechat->toArray());
            } else {
                return Show::json_show(Status::mini_error, "内部错误");
            }
        } else {
            return Show::json_show(Status::mini_error, "操作失败");
        }
    }

    /**
     * 解密手机号
     * @return \think\response\Json
     */
    public function getMobile(){
        $code =$this->request->param('code','','trim');
        $iv =$this->request->param('iv','','trim');
        $openid =$this->request->param('openid','','trim');
        $encryptedData =$this->request->param('encryptedData','','trim');
        $session=$this->mini_app->auth->session($code);

        //查询用户是否存在
        try {
            $user = (new MallUser())->getUserByList($openid);
        } catch (\Exception $e) {
            Log::error("user:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error, "发生错误");
        }
        if (!$user) {
            return Show::json_show(Status::mini_error, "请关闭重试");
        }

        $decryptedData = $this->mini_app->encryptor->decryptData($session['session_key'], $iv, $encryptedData);

        if($decryptedData && isset($decryptedData['phoneNumber'])){
            //(new MallUser())->where("id",'=',$user['id'])->save(array('mobile'=>$decryptedData['phoneNumber']));
            $user->save(['mobile'=>$decryptedData['phoneNumber']]);
        }
        return Show::json_show(Status::mini_normal, "获取用户信息成功", [
            'data'=>$decryptedData
        ]);
    }



    /**
     * 分享绑定分销关系
     * @return \think\response\Json
     */
    public function bindUserLevel(){
        $openid =$this->request->param('openid','','trim');
        $pid =$this->request->param('pid',0,'intval');
        $scane =$this->request->param('scane','','trim');

        if(!empty($scane)){
            $ids =explode('_',$scane);
            $pid =$ids[1];
            if(intval($pid)<=0){
                $pid=0;
            }
        }
        if(mb_strlen($openid) <=25){
            return Show::json_show(Status::mini_normal, "ok", ['status'=>0]);
        }
        if($pid == 0){
            return Show::json_show(Status::mini_normal, "ok", ['status'=>0]);
        }
        try{
            $result =(new MallUser())->getUserByList($openid,'id,nickName,avatarUrl,commission_level,level_time,create_time as donetime');
        }catch (\Exception $e){
            Log::error("userinfo:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error, "发生错误");
        }

        if($result['parent_id'] ==0 && $result['id']!=$pid){
            if(($result['donetime']+300) >= time()){
                $row=$result->save(array('parent_id'=>$pid));
                if($row){
                    return Show::json_show(Status::mini_normal, "ok", ['status'=>1]);
                }else{
                    return Show::json_show(Status::mini_normal, "ok", ['status'=>0]);
                }
            }else{
                return Show::json_show(Status::mini_normal, "ok", ['status'=>0]);
            }
        }else{
            return Show::json_show(Status::mini_normal, "ok", ['status'=>0]);
        }

    }



    /**
     * 用户统计业绩信息
     * @return \think\response\Json
     */
    public function  getCommissions(){
        $openid =$this->request->param('openid','','trim');
        try{
            $result =(new MallUser())->getUserByList($openid,'id,nickName,avatarUrl,commission_level,level_time,parent_id');
            $set=(new MallSetting())->getSettingInfo('teamset');
            if($result && $result['commission_level']>0){
                $commissionlevel =(new MallCommissionLevel())->getlevelInfo($result['commission_level']);
                $result['levelname'] =$commissionlevel['levelname'];
            }else{
                $result['levelname'] ='';
            }
        }catch (\Exception $e){
            Log::error("userinfo:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error, "发生错误");
        }
        if(empty($result)){
            return Show::json_show(Status::mini_error, "用户信息获取失败");
        }
        if($result['parent_id']>0){
            $parentinfo =(new MallUser())->field('nickName')->where("id",'=',$result['parent_id'])->find();
            $result['parentname'] =$parentinfo['nickName'];
        }else{
            $result['parentname'] ='';
        }

        // 显示用户的三个奖励
        $result['commission_first'] =0.00;
        // 直推所有用户
        $commissionlist =(new MallUser())->field('id,openid,nickName')->where("parent_id",$result['id'])->select()->toArray();
        if(!empty($commissionlist)){
            foreach ($commissionlist as $k=>$v){
                $orderscommission =(new MallOrder())->where([['openid','=',$v['openid']],['orderstatus','in',[1,2,3]],['commission','>',0]])->sum('commission');
                $result['commission_first']+=$orderscommission;
            }
        }
        $result['commission_first'] = round($result['commission_first'],2);
        $result['commission_again'] =0.00;
        // 直推复购奖励
        if(!empty($commissionlist)){
            foreach ($commissionlist as $k=>$v){
                $orderscommissionagain =(new MallOrder())->where([['openid','=',$v['openid']],['orderstatus','in',[1,2,3]],['againprice','>',0]])->sum('againprice');
                $result['commission_again']+=$orderscommissionagain;
            }
        }
        $result['commission_again'] = round($result['commission_again'],2);
        $result['commission_team']  =0.00;
        if($set){
            $result['commission_team'] = round($result['commission_again']*$set['option_value']/100,2);
        }
        if($result['level_time']>0){
            $result['level_time'] =date('Y-m-d',$result['level_time']);
        }
        $result['commission_team'] = round($result['commission_team'],2);
        $hasgift =0; // 默认没有礼包
        switch ($result['commission_level']){
            case 3: // 县代
                $count =(new MallOrder())->where("isgife=10")->count();
                if($count==0){
                    $hasgift =1;
                }
                break;
            case 4: // 市代
                $count =(new MallOrder())->where("isgife=11")->count();
                if($count==0){
                    $hasgift =1;
                }
                break;
            case 5: // 省代
                $count =(new MallOrder())->where("isgife=12")->count();
                if($count==0){
                    $hasgift =1;
                }
                break;
            case 6: // 总代
                $count =(new MallOrder())->where("isgife=13")->count();
                if($count==0){
                    $hasgift =1;
                }
                break;
            default:
                break;
        }


        // 统计订单数
        $unpaycount    =(new MallOrder())->where("orderstatus=0 and openid='".$openid."' and deleted=0")->count();
        $paycount      =(new MallOrder())->where("orderstatus=1 and openid='".$openid."' and deleted=0")->count();
        $comfirmcount  =(new MallOrder())->where("orderstatus=2 and openid='".$openid."' and deleted=0")->count();
        $donecount     =(new MallOrder())->where("orderstatus=3 and openid='".$openid."' and deleted=0")->count();
        $servicecount  =(new MallOrder())->where("orderstatus=4 and openid='".$openid."' and deleted=0")->count();

        $result['unpaycount'] =$unpaycount;
        $result['paycount'] =$paycount;
        $result['confirmcount'] =$comfirmcount;
        $result['donecount'] =$donecount;
        $result['servicecount'] =$servicecount;
        return Show::json_show(Status::mini_normal, "ok",[
            'info'=>$result,
            'hasgift'=>$hasgift
        ]);
    }




    /**
     *  商品收藏列表
     * @return \think\response\Json
     */
    public function getCollects(){
        $openid =$this->request->param('openid','','trim');
        try{
            $goods=(new MallCollect())->alias('c')
                ->field('g.id,g.logo,g.title,g.price')
                ->join('mall_goods g','g.id=c.goods_id')
                ->where("c.openid",$openid)
                ->where('g.delete_time',NULL)
                ->select()
                ->toArray();
        }catch (\Exception $e){
            Log::error("user_update_save:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error, "查询失败");
        }
        return Show::json_show(Status::mini_normal, "ok",[
            'goods'=>$goods??[]
        ]);
    }

    /**
     * 我的推广二维码
     * @return \think\response\Json
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     */
    public function mycommissionCode(){
        $openid =$this->request->param('openid','','trim');
        try{
            $userinfo=(new MallUser())->getUserByList($openid,'id,nickName,avatarUrl,commission_level');
            $set=(new MallSetting())->getSettingInfo('is_show');
            if($userinfo && $userinfo['commission_level']>0){
                $commissionlevel =(new MallCommissionLevel())->getlevelInfo($userinfo['commission_level']);
                $userinfo['levelname'] =$commissionlevel['levelname'];
            }else{
                $userinfo['levelname'] ='';
            }
        }catch (\Exception $e){
            Log::error("user_update_save:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error, "查询失败");
        }
        if(empty($userinfo)){
            return Show::json_show(Status::mini_error, "会员不存在");
        }

        $filename='';

        // 生产二维码
        $response = $this->mini_app->app_code->getUnlimit('commission_'.$userinfo['id'], [
            'page'  => 'pages/index/index',
            'width' => 600,
        ]);
        // $response 成功时为 EasyWeChat\Kernel\Http\StreamResponse 实例，失败为数组或你指定的 API 返回类型

        // 保存小程序码到文件
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save(public_path('upload/wxcode/'));
        }

        //使用方法-------------------------------------------------
        $gData = [
            'pic' => $userinfo['avatarUrl'],
            'title' =>htmlspecialchars_decode($userinfo['nickName'])
        ];
        $shareimg =public_path('upload'). $userinfo['id'].'.png';
        Str::createSharePng($userinfo['id'],$gData,'http://'.$_SERVER['HTTP_HOST']. '/upload/wxcode/'.$filename,$shareimg);

        return Show::json_show(Status::mysql_normal,'返回成功',[
            'qrcode' =>'https://'.$_SERVER['HTTP_HOST']. '/upload/wxcode/'.$filename,
            'userinfo'=>$userinfo,
            'set'=>$set,
            'shareimg'=>'https://'.$_SERVER['HTTP_HOST']. '/upload/'.$userinfo['id'].'.png'
        ]);
    }

//    public function demoimg(){
//        $openid =$this->request->param('openid','','trim');
//        try{
//            $userinfo=(new MallUser())->getUserByList($openid,'id,nickName,avatarUrl');
//
//        }catch (\Exception $e){
//            Log::error("user_img:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
//            return Show::json_show(Status::mini_error, "查询失败");
//        }
//        if(empty($userinfo)){
//            return Show::json_show(Status::mini_error, "会员不存在");
//        }
//        //使用方法-------------------------------------------------
//        $gData = [
//            'pic' => $userinfo['avatarUrl'],
//            'title' =>htmlspecialchars_decode($userinfo['nickName'])
//        ];
//        $shareimg =public_path('upload'). $userinfo['id'].'.png';
//        Str::createSharePng($userinfo['id'],$gData,'http://gxsc.jixuantiant.com/upload/wxcode/_commission_6.jpg',$shareimg);
//
//        return Show::json_show(Status::mysql_normal,'返回成功',[
//            'qrcode' =>'https://'.$_SERVER['HTTP_HOST']. '/upload/'.$userinfo['id'].'.png',
//        ]);
//    }




    /**
     * 商品入驻提交
     * @return \think\response\Json
     */
    public function ApplyByGoods(){
        $openid =$this->request->param('openid','','trim');
        $realname =$this->request->param('realname','','trim');
        $mobile =$this->request->param('mobile','','trim');
        $goods_name =$this->request->param('goods_name','','trim');

        if(!$realname || !$mobile || !$goods_name){
            return Show::json_show(Status::mini_error,'商品入驻信息请填写完整');
        }
        if (!preg_match('/^(?:(?:\+|00)86)?1[3-9]\d{9}$/', $mobile)) {
            return Show::json_show(Status::mini_error, '联系电话输入正确手机号');
        }

        try{
            $data =array(
                'openid' =>$openid,
                'realname' =>$realname,
                'mobile'  =>$mobile,
                'goods_name' =>$goods_name
            );
            (new MallApplygoods())->save($data);
        }catch (\Exception $e){
            Log::error("user_update_save:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error,'查询失败');
        }
        return Show::json_show(Status::mini_normal, "提交成功", [

        ]);
    }

    /**
     * 我的商品配置信息
     * @return \think\response\Json
     */
    public function getMallSetting(){
        try{
           $list = (new MallSetting())->getSetting(['mobile','rule']);
        }catch (\Exception $e){
            Log::error("user_update_save:" . $e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            return Show::json_show(Status::mini_error,'查询失败');
        }
        if(empty($list)){
            return Show::json_show(Status::mini_error,'系统配置错误');
        }
        $setting =[];
        foreach ($list as $k=>$v){
            if($v['name'] =='mobile'){
                $setting['mobile'] =$v['option_value'];
            }
            if($v['name'] =='rule'){
                $setting['rule'] =$v['option_value'];
            }
        }
        return Show::json_show(Status::mini_normal, "ok", [
            'setting'=>$setting
        ]);
    }


    /**
     * 我的订单列表
     * @return \think\response\Json
     */
    public function myOrders(){
        $openid =$this->request->param('openid','','trim');
        $status =$this->request->param('status','-1','intval'); // 0 待支付  1待发货 2待收货 3已完成 4售后 9已取消
        $page   =$this->request->param('page',1,'intval');
        if($status==-1){
            $where =[['deleted','=',0],['openid','=',$openid]];
        }else{
            $where =[['deleted','=',0],['orderstatus','=',$status],['openid','=',$openid]];
        }
        try {
            $orders =(new MallOrder())->field('id,ordersn,openid,create_time,orderstatus,payprice')
                ->where($where)
                ->order('orderstatus ASC,id DESC')
                ->page($page,10)
                ->select()
                ->toArray();
            if(!empty($orders)){
                foreach ($orders as $k=>$v){
                    switch ($v['orderstatus']){
                        case 0:
                            $orders[$k]['statusname'] ='待支付';
                            break;
                        case 1:
                            $orders[$k]['statusname'] ='待发货';
                            break;
                        case 2:
                            $orders[$k]['statusname'] ='待收货';
                            break;
                        case 3:
                            $orders[$k]['statusname'] ='已完成';
                            break;
                        case 4:
                            $orders[$k]['statusname'] ='售后/退款';
                            break;
                        default:
                            $orders[$k]['statusname'] ='已取消';
                            break;
                    }

                    $goods =(new MallOrderGoods())->alias('og')->field('og.goods_name,og.image,og.price,og.total,g.thumb_title,og.option_name as get_specs_value')
                        ->join('mall_goods g','g.id=og.goods_id')
                        ->where("order_id",$v['id'])
                        ->select()
                        ->toArray();
                    $orders[$k]['child'] =$goods;
                }
            }
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, "返回成功", [
            'orders' => $orders
        ]);
    }

    /**
     * 订单详情
     * @return \think\response\Json
     */
    public function orderDetail(){
        $order_id = $this->request->param('order_id', '', 'intval');
        $openid = $this->request->param('openid', '', 'trim');
        try {
            $orderinfo = (new MallOrder())->getOrderById([['openid','=',$openid],['id','=',$order_id]]);
            if($orderinfo){
                $goodslist =(new MallOrderGoods())->getByOrderGoodsList($orderinfo['id']);
                $orderinfo['child'] =$goodslist;
            }
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_normal, '查询失败');
        }
        if (empty($orderinfo)) {
            return Show::json_show(Status::mini_normal, '订单不存在');
        }
        switch ($orderinfo['orderstatus']){
            case 0:
                $orderinfo['statusname'] ='待支付';
                break;
            case 1:
                $orderinfo['statusname'] ='待发货';
                break;
            case 2:
                $orderinfo['statusname'] ='待收货';
                break;
            case 3:
                $orderinfo['statusname'] ='已完成';
                break;
            case 4:
                $orderinfo['statusname'] ='售后/退款';
                break;
            default:
                $orderinfo['statusname'] ='已取消';
                break;
        }
        return Show::json_show(Status::mini_normal, "返回成功", [
            'orders' => $orderinfo
        ]);

    }

}